<?php

namespace App\Http\Controllers;

use App\Util\WechatMessage;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class WeChatController extends Controller
{
    /**
     * 服务器响应
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \ReflectionException
     */
    public function serve()
    {
        Log::info('request arrived.');
        $Wechat = $this->wechat();
        $Wechat->server->push(function ($message) {
            switch ($message["MsgType"]) {
                case 'text':
                    $WechatMessage = new WechatMessage($message["Content"]);
                    break;
                case 'event':
                    $WechatMessage = new WechatMessage($message["EventKey"]);
                    break;
            }
            return $WechatMessage->response();
        });
        return $Wechat->server->serve();
    }

    /**
     * 公众号授权登录
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function oauth(Request $request)
    {
        if ($request->input('state') && $request->input('code')) {
            $_data = $request->input();
            $_param = '/app?code=' . $request->input('code');
            foreach($_data as $_k=>$_v) {
                $_param .= '&'.$_k.'='.$_v;
            }
            return redirect(config('app.url').$_param);
        }
    }
}
